<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <PatientListDrawer :patient-list="patientList" :loading="loading" :selected-item="selectedItem" @select="selectPatient" @refresh="getInpRecordList">
        <template #search>
          <SelectArea
            v-model:value="searchParams.bqid"
            use-cache
            post-url
            :post-params="{ wardTypeCodes: ['QYLB001', 'QYLB002'] }"
            @change="getInpRecordList"
          />
        </template>
      </PatientListDrawer>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden" :class="{ 'disabled-style': loading || !selectedItem.inplsh }">
      <PatientInfoHeader :patient-info="selectedItem">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold">{{ selectedItem.bedCode }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="190" :value="selectedItem.ksmc" />
            <LabelValue label="住院号" :width="210" :value="selectedItem.admissionCode" />
            <LabelValue label="入区时间" :width="230" :value="selectedItem.lastDeptRegTime" />
            <!-- <LabelValue label="过敏史" :width="200" tooltip value-class="text-red-600" :value="selectedItem.brGms" /> -->
            <AllergyHistory
              :width="200"
              value-class="text-red-600"
              :value="selectedItem.brGms"
              :patient-info="selectedItem"
              @success="(e) => (selectedItem.brGms = e)"
            />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="190" :value="selectedItem.wardName" />
            <LabelValue label="账户余额" :width="210" :value="formatAmount(selectedItem.yjje) + '元'" />
            <LabelValue label="入院时间" :width="230" :value="selectedItem.admissionTime" />
            <LabelValue label="入院诊断" :width="200" tooltip :value="selectedItem.ryzd" />
          </div>
        </div>
      </PatientInfoHeader>
      <div v-if="!isShowTemperature" class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <div class="flex justify-center mt-4">
            <a-button type="primary" ghost :disabled="loading" @click="checkDay('0')">前一天</a-button>
            <a-date-picker v-model:value="recordDate" value-format="YYYY-MM-DD" class="mx-2 w-32" :disabled="loading" />
            <a-button type="primary" ghost :disabled="loading" @click="checkDay('1')">后一天</a-button>
          </div>
          <a-divider class="my-4" />
          <div>
            <div class="flex justify-between mb-4">
              <a-form :model="formState" name="basic" layout="inline">
                <a-form-item label="测温" name="checkTypeCode" class="w-52">
                  <SelectItem
                    :value="formState.checkTypeCode"
                    type="CWFS00001"
                    placeholder="请选择"
                    @change="
                      (_, $event) => {
                        formState.checkTypeCode = $event?.value || ''
                      }
                    "
                  />
                </a-form-item>
                <a-form-item label="" name="operationStFlag" class="w-8 ml-4">
                  <a-switch v-model:checked="formState.operationStFlag" :un-checked-value="0" :checked-value="1" @change="formState.operationStTime = ''" />
                </a-form-item>
                <a-form-item label="患者今日手术-开始时间" name="operationStTime" class="w-92 ml-2">
                  <!-- :disabled="formState.operationStFlag === 0" -->
                  <a-time-picker v-model:value="formState.operationStTime" value-format="HH:mm" format="HH:mm" placeholder="开始时间" />
                </a-form-item>
                <a-form-item label="" name="operationEdFlag" class="w-8 ml-4">
                  <a-switch v-model:checked="formState.operationEdFlag" :un-checked-value="0" :checked-value="1" @change="formState.operationEdTime = ''" />
                </a-form-item>
                <a-form-item label="患者手术完毕-返室时间" name="operationEdTime" class="w-92 ml-2">
                  <!-- :disabled="formState.operationEdFlag === 0" -->
                  <a-time-picker v-model:value="formState.operationEdTime" value-format="HH:mm" format="HH:mm" placeholder="返室时间" />
                </a-form-item>
                <a-form-item label="出院时间" name="operationEdTime" class="w-92 ml-2">
                  <div>
                    <span class="mr-1">{{ selectedItem?.inpDischarge?.dischargeDate ? selectedItem?.inpDischarge?.dischargeDate : '-' }}</span>
                    <span v-if="selectedItem?.inpDischarge?.ampm === 0">AM</span>
                    <span v-else-if="selectedItem?.inpDischarge?.ampm === 1">PM</span>
                    <span v-else>-</span>
                  </div>
                </a-form-item>
              </a-form>
              <div>
                <a-button type="primary" ghost :disabled="loading" @click="isShowTemperature = true">体温脉搏单</a-button>
                <a-button v-if="formState.auditStatus == 1" type="primary" danger class="ml-2" @click="auditRecord(0)">撤销审核</a-button>
                <a-button v-else type="primary" class="ml-2" @click="auditRecord(1)">审核</a-button>
              </div>
            </div>
            <BaseTable class="mt-2" row-key="id" column-code="000382" :data-source="tableData" :loading="loading">
              <template #bodyCell="{ column, record, index }">
                <div v-if="column.dataIndex === 'tpr'">
                  <EditCell title="体温">
                    <a-input v-model:value="record['tpr' + (index + 1)]" v-input:float placeholder="请输入" suffix="℃" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'review'">
                  <EditCell title="复查" class="flex justify-center items-center">
                    <a-switch v-model:checked="record['review' + (index + 1)]" :un-checked-value="0" :checked-value="1" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'pul'">
                  <EditCell title="脉搏">
                    <a-input v-model:value="record['pul' + (index + 1)]" v-input:int placeholder="请输入" suffix="次/分" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'htr'">
                  <EditCell title="心率">
                    <a-input v-model:value="record['htr' + (index + 1)]" v-input:int placeholder="请输入" suffix="次/分" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'brt'">
                  <EditCell title="呼吸">
                    <a-input v-model:value="record['brt' + (index + 1)]" v-input:int placeholder="请输入" suffix="次/分" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'ltprTypeCode'">
                  <EditCell title="降温方式">
                    <SelectItem
                      v-model:value="record['ltprTypeCode' + (index + 1)]"
                      type="JWFS00001"
                      :select-first="!record['ltprTypeCode' + (index + 1)]"
                      placeholder="请选择"
                    />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'ltpr'">
                  <EditCell title="降温后体温">
                    <a-input v-model:value="record['ltpr' + (index + 1)]" v-input:float placeholder="请输入" suffix="℃" />
                  </EditCell>
                </div>
                <div v-if="column.dataIndex === 'painLevel'">
                  <EditCell title="疼痛程度">
                    <SelectItem
                      :value="record['painLevel' + (index + 1)]"
                      class="w-full !min-w-0"
                      type="DT00315"
                      trigger="init"
                      placeholder="请选择"
                      @change="
                        (_, $event) => {
                          record['painLevel' + (index + 1)] = $event?.value || ''
                        }
                      "
                    />
                  </EditCell>
                </div>
              </template>
            </BaseTable>
            <a-form :model="formState" :label-col="{ style: { width: '100px' } }" class="form-style-flex mt-8">
              <!-- <a-form-item label="舒张压" name="dbp" class="w-3/12">
              <a-input v-model:value="formState.dbp" v-input:float placeholder="请输入" suffix="mmhg" />
            </a-form-item>
            <a-form-item label="收缩压" name="sbp" class="w-3/12">
              <a-input v-model:value="formState.sbp" v-input:float placeholder="请输入" suffix="mmhg" />
            </a-form-item> -->
              <a-form-item label="血压1" name="dbp" class="w-3/12">
                <div class="flex">
                  <a-input v-model:value="formState.sbp" v-input:float placeholder="请输入" class="flex-1" />
                  <div class="mx-2 text-center">/</div>
                  <a-input v-model:value="formState.dbp" v-input:float placeholder="请输入" class="flex-1" suffix="mmHg" />
                </div>
              </a-form-item>
              <a-form-item label="血压2" name="sbp" class="w-3/12">
                <div class="flex">
                  <a-input v-model:value="formState.sbp2" v-input:float placeholder="请输入" class="flex-1" />
                  <div class="mx-2 text-center">/</div>
                  <a-input v-model:value="formState.dbp2" v-input:float placeholder="请输入" class="flex-1" suffix="mmHg" />
                </div>
              </a-form-item>
              <a-form-item label="体重" name="weight" class="w-3/12">
                <a-input v-model:value="formState.weight" placeholder="请输入" suffix="kg" />
              </a-form-item>
              <a-form-item label="身高" name="height" class="w-3/12">
                <a-input v-model:value="formState.height" v-input:float placeholder="请输入" suffix="cm" />
              </a-form-item>
              <a-form-item label="尿量" name="untOutput" class="w-3/12">
                <a-input v-model:value="formState.untOutput" v-input:float placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="痰量" name="sptOutput" class="w-3/12">
                <a-input v-model:value="formState.sptOutput" v-input:float placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="引流量" name="dngOutput" class="w-3/12">
                <a-input v-model:value="formState.dngOutput" v-input:float placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="呕吐量" name="vomitOutput" class="w-3/12">
                <a-input v-model:value="formState.vomitOutput" v-input:float placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="总入量" name="intake" class="w-3/12">
                <a-input v-model:value="formState.intake" v-input:float placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="总出量" name="output" class="w-3/12">
                <a-input v-model:value="formState.output" v-input:float disabled placeholder="请输入" suffix="ml" />
              </a-form-item>
              <a-form-item label="大便次数" name="dftFqc" class="w-3/12">
                <a-input v-model:value="formState.dftFqc" v-input:int placeholder="请输入" suffix="次" />
              </a-form-item>
              <a-form-item label="小便次数" name="untFqc" class="w-3/12">
                <a-input v-model:value="formState.untFqc" v-input:int placeholder="请输入" suffix="次" />
              </a-form-item>
              <a-form-item label="血氧" name="untFqc" class="w-3/12">
                <a-input v-model:value="formState.spo2" v-input:float placeholder="请输入" suffix="%" />
              </a-form-item>
            </a-form>
            <div class="flex justify-end mt-8">
              <a-button type="primary" ghost @click="getData()">重置</a-button>
              <a-button type="primary" class="ml-2" :disabled="formState.auditStatus === 1" @click="saveData">保存</a-button>
            </div>
          </div>
        </a-card>
      </div>
      <div v-else class="h-full">
        <TabTemperature :key="selectedItem.inplsh" :inplsh="selectedItem.inplsh" is-show-back @back="isShowTemperature = false" />
      </div>
    </div>
    <!-- <div class="absolute -top-[9999px]">
      <a-button ref="printRef" v-print="{ id: 'printDom' }" type="primary">打印</a-button>
      <iframe
        v-if="iframeUrl"
        id="printDom"
        class="w-[1150px] "
        name="iframe"
        :src="iframeUrl"
        width="100%"
        height="100%"
        frameborder="0"
      ></iframe>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import BaseTable from '@/components/BaseTable'
import { getSystemConfig } from '@/utils/systemConfig'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import PatientListDrawer from '@/components/business/PatientListDrawer'
import TabTemperature from '@/views/in-doctor/workstation/components/TabTemperature'
import LabelValue from '@/components/LabelValue'
import { formatAmount } from '@/utils/format'
import { post } from '@/utils/request'

const route = useRoute()
const recordDate = ref(dayjs().format('YYYY-MM-DD'))
const patientList = ref([])
const selectedItem = ref({})
const formState = ref({
  operationStFlag: 0,
  operationEdFlag: 0
})
const isShowTemperature = ref(false)
const defaultCheckType = ref('')
const tableData = ref([])
const getData = async () => {
  formState.value.checkTypeCode = ''
  const { code, data, msg } = await post('/inp/zyhs/getInpTpRecordResponseList', {
    inplsh: selectedItem.value.inplsh,
    recordDate: recordDate.value
  })
  tableData.value = []
  if (code !== 0) return message.error(msg)
  if (data) {
    formState.value = data
    //INP_TEMPERATURE_RECORD_STYLE 体温脉搏单的时点样式  0：通用26时点|1：安徽37时点
    const timeData = getSystemConfig('INP_TEMPERATURE_RECORD_STYLE') === '0' ? ['02', '06', '10', '14', '18', '22'] : ['03', '07', '11', '15', '19', '23']
    tableData.value = []
    let obj = {}
    timeData.forEach((item, index) => {
      obj = {}
      obj.time = item
      obj['tpr' + (index + 1)] = data['tpr' + (index + 1)] || ''
      obj['review' + (index + 1)] = data['review' + (index + 1)] || 0
      obj['pul' + (index + 1)] = data['pul' + (index + 1)] || ''
      obj['htr' + (index + 1)] = data['htr' + (index + 1)] || ''
      obj['brt' + (index + 1)] = data['brt' + (index + 1)] || ''
      obj['ltprTypeCode' + (index + 1)] = data['ltprTypeCode' + (index + 1)] || ''
      obj['ltpr' + (index + 1)] = data['ltpr' + (index + 1)] || ''
      obj['painLevel' + (index + 1)] = data['painLevel' + (index + 1)] || ''
      tableData.value.push(obj)
    })
  } else {
    tableData.value = []
    formState.value = {
      operationStFlag: 0,
      operationEdFlag: 0
    }
    const timeData = getSystemConfig('INP_TEMPERATURE_RECORD_STYLE') === '0' ? ['02', '06', '10', '14', '18', '22'] : ['03', '07', '11', '15', '19', '23']
    let obj = {}
    timeData.forEach((item, index) => {
      obj = {}
      obj.time = item
      obj['tpr' + (index + 1)] = ''
      obj['review' + (index + 1)] = 0
      obj['pul' + (index + 1)] = ''
      obj['htr' + (index + 1)] = ''
      obj['brt' + (index + 1)] = ''
      obj['ltprTypeCode' + (index + 1)] = ''
      obj['ltpr' + (index + 1)] = ''
      obj['painLevel' + (index + 1)] = ''
      tableData.value.push(obj)
    })
    setDefaultCheckType()
  }
}
const setDefaultCheckType = async () => {
  const { data = [], code } = await post('/operation/opex/getDictCommonItemList', { dictCommonCode: 'CWFS00001', status: 1 })
  if (code === 0 && data && data.length > 0) {
    let checkType = '' //0：腋测| 1：口测 |2：肛测  |3:电子测温
    if (defaultCheckType.value === '0') {
      checkType = '腋温'
    } else if (defaultCheckType.value === '1') {
      checkType = '口温'
    } else if (defaultCheckType.value === '2') {
      checkType = '肛温'
    } else if (defaultCheckType.value === '3') {
      checkType = '电子测温'
    } else {
      return
    }
    const outData = data.filter((item) => {
      return item.dictItemName.includes(checkType)
    })
    if (outData && outData.length > 0) {
      // formState.value.dictItemName = outData[0].dictItemName
      formState.value.checkTypeCode = outData[0].dictItemCode
    }
  }
}

const saveData = async () => {
  tableData.value.forEach((item) => {
    formState.value = { ...formState.value, ...item, time: undefined }
  })
  const { code, msg } = await post(
    '/inp/zyhs/doSaveInpTpRecord',
    {
      inplsh: selectedItem.value.inplsh,
      recordDate: recordDate.value,
      ...formState.value,
      operationStTime: formState.value.operationStTime ? formState.value.operationStTime : '',
      operationEdTime: formState.value.operationEdTime ? formState.value.operationEdTime : ''
    },
    {
      loading: true
    }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg || '保存成功')
  getData()
}
const auditRecord = async (type) => {
  if (!formState.value.id) return message.error('请先保存单据')
  const { code, msg } = await post('/inp/zyhs/doModifyInpTpRecord', {
    auditStatus: type,
    id: formState.value.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  getData()
}
const loading = ref(false)
const searchParams = ref({
  bqid: ''
})
// 获取左侧患者列表
const getInpRecordList = async () => {
  loading.value = true
  selectedItem.value = {} // 清空选中的患者
  const { code, data, msg } = await post('/inp/inpComprehensive/getInpRecordInfo', {
    bqid: searchParams.value.bqid
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  patientList.value = data
  if (data && data.length > 0) {
    if (route.query?.inplsh) {
      selectedItem.value = data.find((item) => item.inplsh === route.query?.inplsh) || {}
    } else {
      selectedItem.value = data[0]
    }
    selectedItem.value.inplsh && getData()
  } else {
    formState.value = {
      operationStFlag: 0,
      operationEdFlag: 0
    }
    tableData.value = []
  }
}
const selectPatient = (patient) => {
  selectedItem.value = patient
  getData()
}

const checkDay = (type) => {
  if (type === '1') {
    recordDate.value = dayjs(recordDate.value).add(1, 'day').format('YYYY-MM-DD')
  } else {
    recordDate.value = dayjs(recordDate.value).subtract(1, 'day').format('YYYY-MM-DD')
  }
  getData()
}

watchEffect(() => {
  const output =
    (Number(formState.value.untOutput) || 0) +
    (Number(formState.value.sptOutput) || 0) +
    (Number(formState.value.dngOutput) || 0) +
    (Number(formState.value.vomitOutput) || 0)
  formState.value.output = output || ''
})
onMounted(() => {
  getInpRecordList()
  defaultCheckType.value = getSystemConfig('INP_NURSE_TAKE_TEMPERATURE_DEFAULT_WAY_CODE') //0：腋测| 1：口测 |2：肛测
})
</script>
<style lang="less" scoped>
.bg-color {
  background: var(--thin-color);
}
:deep(.ant-table-row-expand-icon) {
  display: none;
}
.classify-checkall {
  .ant-tag {
    font-size: 14px;
    line-height: 30px;
    padding-inline: 14px;
  }
}
</style>
